import React, { Component } from 'react'
import { HashRouter as Router, NavLink, Route, Switch, Redirect } from 'react-router-dom'
import { imgInter } from '../../data/Interface'
import './detail.css'
import Details from './Detail/Details';
import Evaluation from './Detail/Evaluation';
import AddToMap from './Detail/AddToMap';
import { addshoucang, addyuding, delyuding, delshoucang, getMsg, getyudinglist, getshoucanglist } from '../../redux/actionCreator';
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { ActionSheet, Toast } from 'antd-mobile';
import 'react-share-components/dist/react-share-components.css'
import { addDyshopReport } from '../../redux/actionCreator/report'
import { Modal, Button, WhiteSpace, WingBlank } from 'antd-mobile';

import { DatePicker, List } from 'antd-mobile';
import enUs from 'antd-mobile/lib/date-picker/locale/en_US';
import pxPage from '../../root/pxPage';

const nowTimeStamp = Date.now();
const now = new Date(nowTimeStamp);
// GMT is not currently observed in the UK. So use UTC now.
const utcNow = new Date(now.getTime() + (now.getTimezoneOffset() * 60000));

// Make sure that in `time` mode, the maxDate and minDate are within one day.
let minDate = new Date(nowTimeStamp - 1e7);
const maxDate = new Date(nowTimeStamp + 1e7);
// console.log(minDate, maxDate);
if (minDate.getDate() !== maxDate.getDate()) {
    // set the minDate to the 0 of maxDate
    minDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate());
}

function formatDate(date) {
    /* eslint no-confusing-arrow: 0 */
    const pad = n => n < 10 ? `0${n}` : n;
    const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
    const timeStr = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
    return `${dateStr} ${timeStr}`;
}

// If not using `List.Item` as children
// The `onClick / extra` props need to be processed within the component
const CustomChildren = ({ extra, onClick, children }) => (
    <div
        onClick={onClick}
        style={{ backgroundColor: '#fff', height: '45px', lineHeight: '45px', padding: '0 15px' }}
    >
        {children}
        <span style={{ float: 'right', color: '#888' }}>{extra}</span>
    </div>
);



const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
const alert = Modal.alert;
const operation = Modal.operation;
const prompt = Modal.prompt;
if (isIPhone) { }

let bool = false;
const exitappoint = (props) => {
    // 在yuding中筛选出与本页相同的商品
    let appbool = false
    props.yuding.map((item) => {
        if (item.commodity_id == JSON.parse(localStorage.getItem('commoditydetail')).commodity_id) {
            appbool = true
        }
    })

    if (!appbool) {
        bool = false;
    } else {
        bool = true;
    }
    return bool;
}

let cobool = false;
const exitcollect = (props) => {
    let appbool = false
    props.shoucang.map((item) => {
        console.log(item);
        if (item.commodity_id == JSON.parse(localStorage.getItem('commoditydetail')).commodity_id) {
            appbool = true
        }
    })

    if (!appbool) {
        cobool = false;
    } else {
        cobool = true;
    }
    return cobool;
}

class Detail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            date: now,
            time: now,
            utcDate: utcNow,
            dpValue: null,
            customChildValue: null,
            visible: false,

            clicked: 'none',
            clicked1: 'none',
            clicked2: 'none',
            yuding_state: exitappoint(this.props) ? "已预约" : "点击预约",
            shoucang_state: exitcollect(this.props) ? "xin" : "xin1",
        };

        this.props.dispatch(getyudinglist(getMsg(this.props).user_id))
        this.props.dispatch(getshoucanglist(getMsg(this.props).user_id))
    }

    dataList = [
        // { url: 'OpHiXAcYzmPQHcdlLFrc', title: '发送给朋友' },
        { url: 'wvEzCMiDZjthhAOcwTOu', title: '新浪微博' },
        { url: 'cTTayShKtEIdQVEMuiWt', title: 'QQ空间' },
        { url: 'umnHwvEgSyQtXlZjNJTt', title: '微信好友' },
        { url: 'SxpunpETIwdxNjcJamwB', title: 'QQ' },
    ].map(obj => ({
        icon: <img src={`https://gw.alipayobjects.com/zos/rmsportal/${obj.url}.png`} alt={obj.title} style={{ width: 36 }} />,
        title: obj.title,
    }));

    showShareActionSheet = () => {
        ActionSheet.showShareActionSheetWithOptions({
            options: this.dataList,
            cancelButtonIndex: -1,
            title: `百果园·${JSON.parse(localStorage.getItem('busdetail')).business_name}·${JSON.parse(localStorage.getItem('commoditydetail')).commodity_title}`,
            message: '选择要分享到的平台',
        }, (buttonIndex) => {
            this.setState({ clicked1: buttonIndex > -1 ? this.dataList[buttonIndex].title : 'cancel' });
            // also support Promise
            return new Promise((resolve) => {
                console.log("buttonIndex!!!!:", buttonIndex)
                switch (buttonIndex) {
                    // weibo
                    case 0:
                        Toast.info('正在跳转到分享界面');
                        setTimeout(resolve, 500);
                        window.location.href = `https://service.weibo.com/share/share.php?url=https%3A%2F%2Fgithub.com%2Fliuguanhua%2Freact-share-components&title=react-share-components&pic=&appkey=#_loginLayer_1607479540650`
                        break;
                    //qqzone
                    case 1:
                        Toast.info('正在跳转到分享界面');
                        setTimeout(resolve, 500);
                        window.location.href = `https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=https%3A%2F%2Fgithub.com%2Fliuguanhua%2Freact-share-components&title=react-share-components&desc=%E4%B8%80%E9%94%AE%E5%88%86%E4%BA%AB%E5%88%B0%E5%90%84%E7%A4%BE%E4%BA%A4%E5%B9%B3%E5%8F%B0&summary=&site=%E7%99%BE%E6%9E%9C%E5%9B%AD&pics=`
                        break;
                    //douban
                    case 2:
                        Toast.info('正在跳转到分享界面');
                        setTimeout(resolve, 500);
                        window.location.href = `https://accounts.douban.com/passport/login?redir=https%3A//www.douban.com/share/service%3Fhref%3Dhttps%253A%252F%252Fgithub.com%252Fliuguanhua%252Freact-share-components%26name%3Dreact-share-components%26text%3D%25E4%25B8%2580%25E9%2594%25AE%25E5%2588%2586%25E4%25BA%25AB%25E5%2588%25B0%25E5%2590%2584%25E7%25A4%25BE%25E4%25BA%25A4%25E5%25B9%25B3%25E5%258F%25B0%26image%3D%26starid%3D0%26aid%3D0%26style%3D11`
                        break;
                    // qq
                    case 3:
                        Toast.info('正在跳转到分享界面');
                        setTimeout(resolve, 500);
                        window.location.href = `https://connect.qq.com/widget/shareqq/index.html?url=https%3A%2F%2Fgithub.com%2Fliuguanhua%2Freact-share-components&title=react-share-components&source=%E7%99%BE%E6%9E%9C%E5%9B%AD&desc=%E4%B8%80%E9%94%AE%E5%88%86%E4%BA%AB%E5%88%B0%E5%90%84%E7%A4%BE%E4%BA%A4%E5%B9%B3%E5%8F%B0&pics=&summary=`
                        break;
                    default:
                        Toast.info('取消分享');
                        setTimeout(resolve, 500);
                        break;
                }
            });
        });
    }

    formatDate = (now) => {
        //取得4位数的年份
        let year = now.getFullYear();
        //取得日期中的月份，其中0表示1月，11表示12月
        let month = now.getMonth() + 1;
        //返回日期月份中的天数（1到31）；如果天数是个位数就在数字前加上0
        let date = now.getDate() < 10 ? '0' + now.getDate() : now.getDate();

        return year + "-" + month + "-" + date
    }

    render() {
        const str = "2018-11-30"
        // 日期正则表达式
        const timeRegex1 = new RegExp("(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|" +
            "((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|" +
            "((0[48]|[2468][048]|[3579][26])00))-02-29)$");
        console.log(str.match(timeRegex1))
        // const dateRegex = new Regex("(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$");

        return (
            <div className="detail" style={{ minHeight: '100vh', display: 'flex' }}>
                <div style={{ backgroundColor: "#080904", minHeight: '100vh', display: 'flex', width: '100%' }}>
                    <div style={{ width: '100%', margin: '0 auto' }}>

                        <div className="detail-top" style={{ paddingTop: '2em', position: 'fixed', top: '0', width: '100%', height: '40px' }}>

                            {/* 返回按键 */}
                            <span style={{ position: 'absolute', left: '1em' }}>
                                <i
                                    className="iconfont icon-fanhui"
                                    style={{ fontSize: '1.7em' }}
                                    onClick={() => this.props.history.goBack()}
                                >
                                </i>
                            </span>

                            {/* 分享按键 */}
                            <span style={{ position: 'absolute', right: '1em' }}>
                                <i
                                    onClick={
                                        this.showShareActionSheet
                                        // () => this.props.history.push('/share')
                                    }
                                    className="iconfont icon-fenxiang"
                                    style={{ fontSize: '1.7em' }}
                                ></i>
                            </span>

                        </div>

                        {/* 详情页背景图 */}
                        <div
                            style={{ textAlign: 'center', fontSize: '1.5em', fontWeight: 'bold', width: '100%', height: '12em', background: `url(${imgInter + JSON.parse(localStorage.getItem('commoditydetail')).commodity_pic}) no-repeat fixed top` }}
                        >
                            <div style={{ paddingTop: '10em', }}></div>
                            {/* 果园名 */}
                            <div
                                className="detail-title"
                                style={{ height: '4em', width: '100%', lineHeight: '2em' }}
                            >
                                {JSON.parse(localStorage.getItem('busdetail')).business_name}·{JSON.parse(localStorage.getItem('commoditydetail')).commodity_title}
                            </div>
                        </div>

                        <Router>

                            <ul style={{ textAlign: 'center' }} className="detail-navlink">
                                <li><NavLink activeClassName='active' activeStyle={{ color: 'orange', borderBottom: '1px solid orange' }} to={`/detail/details`}>详情</NavLink></li>
                                <li><NavLink activeClassName='active' activeStyle={{ color: 'orange', borderBottom: '1px solid orange' }} to={`/detail/details`} to={`/detail/map`}>地址</NavLink></li>
                                <li><NavLink activeClassName='active' activeStyle={{ color: 'orange', borderBottom: '1px solid orange' }} to={`/detail/details`} to={`/detail/evaluation`}>评论</NavLink></li>
                            </ul>

                            <Switch>
                                <Route exact path={`/detail/details`} component={Details} />
                                <Route path={`/detail/map`} component={AddToMap} />
                                <Route path={`/detail/evaluation`} component={Evaluation} />
                                <Route render={() => <Redirect to={`/detail/details`} />} />
                            </Switch>
                        </Router>

                        {/* 固定在详情页底部的私信预约信息 */}
                        <div style={{ position: 'fixed', bottom: '0', backgroundColor: 'rgba(47,49,67)', width: '100%', borderTopLeftRadius: '40px', borderTopRightRadius: '40px', zIndex: '5' }}>

                            <span style={{ position: 'absolute', right: '1.5em', marginTop: pxPage(15) }}>

                                {/* 点击收藏 */}
                                <button
                                    style={{ height: pxPage(40), width: pxPage(40) }}
                                    onClick={
                                        () => (exitcollect(this.props)) ?
                                            (
                                                this.props.dispatch(delshoucang(getMsg(this.props).user_id, JSON.parse(localStorage.getItem('commoditydetail')).commodity_id, JSON.parse(localStorage.getItem('commoditydetail')))),
                                                this.setState({ shoucang_state: 'xin1' })
                                            )
                                            :
                                            (
                                                this.props.dispatch(addshoucang(getMsg(this.props).user_id, JSON.parse(localStorage.getItem('commoditydetail')).commodity_id, JSON.parse(localStorage.getItem('commoditydetail')))),
                                                this.setState({ shoucang_state: 'xin' })
                                            )

                                    }
                                    className="details-collect"
                                >
                                    <i className={`iconfont icon-${this.state.shoucang_state}`}></i>
                                </button>

                                {/* 点击预约 */}
                                <button
                                    style={{ height: pxPage(40), width: pxPage(80) }}
                                    onClick={
                                        () => (exitappoint(this.props)) ?
                                            (
                                                this.props.dispatch(delyuding(getMsg(this.props).user_id, JSON.parse(localStorage.getItem('commoditydetail')).commodity_id, JSON.parse(localStorage.getItem('commoditydetail')))),
                                                this.setState({ yuding_state: '点击预约！' })
                                            )
                                            :
                                            (

                                                //跳转到详情页
                                                // this.props.history.push({
                                                //     pathname: '/appointdetail',
                                                //     // search:'user=${}&'
                                                // })

                                                prompt('请输入您的预约时间', 'defaultValue for prompt', [
                                                    { text: '取消' },
                                                    {
                                                        text: '确定', onPress: value => {
                                                            console.log(`输入的内容:${value}`)
                                                            if (value) {
                                                                if (value.match(timeRegex1)) {
                                                                    this.props.dispatch(addyuding(getMsg(this.props).user_id, JSON.parse(localStorage.getItem('commoditydetail')).commodity_id, JSON.parse(localStorage.getItem('commoditydetail')), value))
                                                                    this.setState({ yuding_state: '已预约！' })
                                                                } else {
                                                                    Toast.fail('您输入的日期格式不正确', 2)
                                                                }
                                                            } else {
                                                                Toast.fail('您输入的时间为空', 2)
                                                            }

                                                        }
                                                    },
                                                ], '', this.formatDate(new Date()))

                                            )
                                    }

                                    className="details-appoint"
                                >
                                    {this.state.yuding_state}
                                </button>

                            </span>

                            <ul className="details-li">
                                {/* 客服聊天 */}
                                <li
                                    onClick={() => {
                                        this.props.history.push({
                                            pathname: '/kefu',
                                            search: `business_id=${JSON.parse(localStorage.getItem('commoditydetail')).business_id}`
                                        })
                                    }}>
                                    <i className="iconfont icon-kefu"></i>
                                </li>

                                {/* 查看预约表 */}
                                <li
                                    onClick={() => { this.props.history.push('/appo') }}>
                                    <i className="iconfont icon-ziyuan"></i>
                                    {/* {comm.commodity_appoint} */}
                                </li>

                                {/* 查看收藏夹 */}
                                <li
                                    onClick={() => { this.props.history.push('/collect') }}>
                                    <i className="iconfont icon-ico_shoucangjia"></i>
                                    {/* {comm.commodity_collect} */}
                                </li>
                                <li>
                                    <i
                                        // 这里写点击举报
                                        onClick={() => prompt('举报原因', 'defaultValue for prompt', [
                                            { text: '取消', onPress: () => { console.log('点击了取消') } },
                                            {
                                                text: '确认', onPress: value => {

                                                    this.props.dispatch(addDyshopReport(JSON.parse(localStorage.getItem('user')).user_id, value, JSON.parse(localStorage.getItem('commoditydetail')).commodity_id))
                                                    console.log(`输入的内容:${value}`)
                                                    Toast.success('举报成功！', 1)
                                                }
                                            },
                                        ], 'default', '')}
                                        className="iconfont icon-jubao2"
                                        style={{ color: 'white' }}></i>
                                </li>
                            </ul>
                        </div>

                    </div>

                </div>

                <div style={{ flex: '1' }}></div>
            </div>
        )
    }
}

const mapStateToProps = (state) => (
    {
        shop: state.shop,
        shoucang: state.shoucang,
        yuding: state.yuding,
        login: state.login
    }
)

export default withRouter(connect(mapStateToProps)(Detail))
